What is jest-matcher-utils?
The jest-matcher-utils package provides utility functions for creating custom Jest matchers. It is designed to help developers write their own matchers that integrate seamlessly with Jest's built-in expectation system, offering a way to extend Jest's assertion capabilities with custom logic. The utilities provided by this package include formatting values for error messages, comparing values, and generating matcher error messages.
What are jest-matcher-utils's main functionalities?
pretty-format
Formats any JavaScript value for pretty printing, which is useful for generating readable error messages in custom matchers.
const { prettyFormat } = require('jest-matcher-utils');
console.log(prettyFormat({ foo: 'bar' }));
matcherHint
Generates a hint string for a matcher, which can be used at the beginning of error messages to indicate which matcher failed.
const { matcherHint } = require('jest-matcher-utils');
console.log(matcherHint('.toBe'));
printExpected and printReceived
These functions format the expected and received values to be included in error messages, applying color highlighting to improve readability.
const { printExpected, printReceived } = require('jest-matcher-utils');
console.log(`Expected: ${printExpected(true)}
Received: ${printReceived(false)}`);
Other packages similar to jest-matcher-utils
chai
Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework. It offers similar functionality to jest-matcher-utils in the sense that it provides a rich set of assertions and plugins to extend its capabilities. However, Chai is a standalone assertion library, not tied to any specific test runner like Jest.
expect
Expect is a minimalist assertion library that comes with Jest but can also be used independently. It provides a similar API for writing test assertions as jest-matcher-utils, but jest-matcher-utils focuses more on the utilities for creating custom matchers rather than providing a comprehensive set of built-in matchers.
jest-matcher-utils
This package's exports are most notably used by expect
's this.utils
.
Installation
To add this package as a dependency of a project, run either of the following commands:
npm install jest-matcher-utils
yarn add jest-matcher-utils
Functions
stringify
highlightTrailingWhitespace
printReceived
printExpected
printWithType
ensureNoExpected
ensureActualIsNumber
ensureExpectedIsNumber
ensureNumbers
ensureExpectedIsNonNegativeInteger
printDiffOrStringify
diff
pluralize
getLabelPrinter
matcherErrorMessage
matcherHint
Types
MatcherHintOptions
DiffOptions
Constants
EXPECTED_COLOR
RECEIVED_COLOR
INVERTED_COLOR
BOLD_WEIGHT
DIM_COLOR
SUGGEST_TO_CONTAIN_EQUAL